package com.kitty.service.impl;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.kitty.dao.impl.UserDao;
import com.kitty.model.TUser;
import com.kitty.service.IUserMgr;
import com.kitty.util.BaseException;
import com.kitty.util.StringUtil;

public class UserMgr implements IUserMgr{
	private UserDao userDao;
	protected Log logger = (Log)LogFactory.getLog(UserMgr.class);
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public String addUser(TUser user) throws BaseException {
		try {
			return userDao.save(user);
			
		} catch(Exception ex) {
			logger.warn("error at UserMgr.addUser: " + ex.getMessage());
			throw new BaseException("增加用户时出现以下错误：" + ex.getMessage());
		}
	}
	
	public String addUser(String id, String email, String pwd, String name, Date validTo) throws BaseException {
		try {
			StringUtil su = new StringUtil();
			TUser user = new TUser();
			
			user.setId(id);
			user.setEmail(email);
			user.setPwd_salt(su.getRandomString(8));
			user.setPwd_hash(su.getMD5Str(pwd + user.getPwd_salt()));
			user.setName(name);
			user.setValidTo(validTo);
			
			userDao.save(user);
			return user.id;
		} catch(Exception ex) {
			logger.warn("error at UserMgr.addUser: " + ex.getMessage());
			throw new BaseException("保存用户时出现错误: " + ex.getMessage());
		}
	}
	
	public TUser checkLogin(String email, String pwd) throws BaseException {
		try {
			TUser user = userDao.findUserByEmail(email);
			if (user != null) {
				if (!user.pwd_hash.equals(new StringUtil().getMD5Str(pwd + user.pwd_salt))) {
					user = null;
				}
			}
			
			return user;
			
		} catch(Exception ex) {
			logger.warn("error at UserMgr.checkLogin: " + ex.getMessage());
			throw new BaseException("登录验证时出现以下错误：" + ex.getMessage());
		}
	}
}
